package felix.things.router.mqtt.server.store.session;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import felix.things.router.mqtt.server.common.session.ISessionStoreService;
import felix.things.router.mqtt.server.common.session.SessionStore;
import felix.things.router.mqtt.server.store.utils.StoreUtil;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

/**
 * 会话存储服务
 *
 * @author Felix
 * @date 2019/8/21
 */
@Service
public class SessionStoreServiceImpl implements ISessionStoreService {
    private final static String CACHE_PRE = "mqtt-server:session:";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void put(String clientId, SessionStore sessionStore, int expire) {
        //SessionStore对象不能正常转为JSON,使用工具类类解决
        Map<String, Object> session = StoreUtil.transPublishToMapBeta(sessionStore);

        if (session != null) {
            if (expire > 0) {
                redisTemplate.opsForValue().set(CACHE_PRE + clientId, JSON.toJSONString(session), expire, TimeUnit.SECONDS);
            } else {
                redisTemplate.opsForValue().set(CACHE_PRE + clientId, JSON.toJSONString(session));
            }
        }
    }

    @Override
    public void expire(String clientId, int expire) {
        redisTemplate.expire(CACHE_PRE + clientId, expire, TimeUnit.SECONDS);
    }

    @Override
    public SessionStore get(String clientId) {
        String jsonObj = redisTemplate.opsForValue().get(CACHE_PRE + clientId);
        if (Strings.isNotBlank(jsonObj)) {
            HashMap<String, Object> map = JSON.parseObject(jsonObj, new TypeReference<HashMap<String, Object>>() {
            });
            return StoreUtil.mapTransToPublishMsgBeta(map);
        }
        return null;
    }

    @Override
    public boolean containsKey(String clientId) {
        return Optional.ofNullable(redisTemplate.hasKey(CACHE_PRE + clientId)).orElse(false);
    }

    @Override
    @Async
    public void remove(String clientId) {
        redisTemplate.delete(CACHE_PRE + clientId);
    }
}
